package com.he.services.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.github.pagehelper.PageHelper;
import com.he.mapper.DeptMapper;
import com.he.mapper.UserMapper;
import com.he.pojo.ServiceResult;
import com.he.pojo.User;
import com.he.services.DingTokenService;
import com.he.services.UserService;
import com.he.util.PwdUtil;
import com.taobao.api.ApiException;
import org.apache.tomcat.jni.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.he.config.UrlConstant.URL_DEPARTMENT_LIST;
import static com.he.config.UrlConstant.URL_V2_USER_LIST;

/**
 * @program: usersync
 * @description:
 * @author: xin.he
 * @create: 2021-06-06 13:10
 **/
@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    DeptMapper deptMapper;

    @Autowired
    DingTokenService dingTokenService;

    @Override
    public List<User> queryAll() {
        return userMapper.queryAll();
    }

    @Override
    public int add(User user) {
        return userMapper.add(user);
    }

    @Override
    public User queryByName(String name) {
        return userMapper.queryByName(name);
    }

    @Override
    public User queryByUid(String uid) {
        return userMapper.queryByUid(uid);
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<User> pageUserList(int pageNum, int pageSize){
        PageHelper.startPage(pageNum , pageSize);
        List<User> list = userMapper.queryAll();
        return list;
    }

    /**
     * 同步用户
     * @return
     * @throws Exception
     */
    public String syncUser() throws Exception {
        List<String> deptIds = deptMapper.getDeptIdList();
        // 获取accessToken
        ServiceResult<String> accessTokenSr = dingTokenService.getAccessToken();
        if (!accessTokenSr.isSuccess()){
            throw new Exception("获取accessToken失败:" + accessTokenSr.getMessage());
        }
        String accessToken = accessTokenSr.getResult();

        for (String did : deptIds){
            Map<String,Long> hasMap = new HashMap<>();
            hasMap.put("hasMore",1L);
            hasMap.put("nextCursor",0L);
            while (hasMap.get("hasMore").equals(1L)){
                Map<String,Long> newMap = getUserList(did,accessToken, hasMap.get("nextCursor"));
                hasMap.clear();
                hasMap.put("hasMore",newMap.get("hasMore"));
                hasMap.put("nextCursor",newMap.get("nextCursor"));
            }
        }
        return "正在同步用户。。。";
    }

    /**
     * 获取部门用户
     * @param did
     * @param token
     * @return 返回下一批的游标
     */
    public Map<String,Long> getUserList(String did , String token, Long cursor){
        DingTalkClient client = new DefaultDingTalkClient(URL_V2_USER_LIST);
        OapiV2UserListRequest request = new OapiV2UserListRequest();
        request.setHttpMethod("GET");
        request.setDeptId(Long.valueOf(did));
        request.setCursor(cursor);
        request.setSize(100L);

        OapiV2UserListResponse response = null;
        try {
            response = client.execute(request, token);
        } catch (ApiException e) {
            log.error("获取钉钉部门列表失败{}", URL_DEPARTMENT_LIST, e);
        }
        List<OapiV2UserListResponse.ListUserResponse> list = response.getResult().getList();
        for (OapiV2UserListResponse.ListUserResponse dingUser : list){
            User u = new User();
            u.setDeptId(did);
            u.setAlisName(dingUser.getName());
            long time = System.currentTimeMillis();
            u.setCreateTime(Long.toString(time));
            u.setName(dingUser.getUserid());
            u.setDeleted(false);
            u.setEmail(dingUser.getEmail());
            u.setPhone(dingUser.getMobile());
            u.setUid(dingUser.getJobNumber());
            u.setSex("unknown");
            u.setStatus(dingUser.getActive().toString());
            u.setPwd(PwdUtil.getCharAndNum(8));
            userMapper.add(u);
        }
        Boolean hasMore = response.getResult().getHasMore();//是否有下一批
        if (hasMore){
            Long nextCursor = response.getResult().getNextCursor() ;
            Map<String,Long> map = new HashMap<>();
            map.put("hasMore", 1L);//1表示有下一批
            map.put("nextCursor", nextCursor);
            return map;
        }
        else {
            Map<String,Long> map = new HashMap<>();
            map.put("hasMore", 0L);//0表示没有下一批
            map.put("nextCursor", 0L);
            return map;
        }
    }


}
